<template>
  <div class="app-container">
    <div class="filter-container">
      <p style="display:inline-block;margin-left:2%">活动状态：</p>
      <el-select
        size="small"
        placeholder="请选择状态"
        clearable
        class="filter-item"
        style="width: 250px;margin-left:2%"
        v-model="listQuery.status"
      >
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
      </el-select>
      <p style="display:inline-block;margin-left:2%">起止时间：</p>
      <el-date-picker
        v-model="value1"
        type="datetimerange"
        range-separator="至"
        value-format="yyyy-MM-dd HH:mm:ss"
        start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>
      <el-button
        size="small"
        class="filter-item"
        type="success"
        icon="el-icon-search"
        style="margin-left:3%"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
          size="small"
          class="filter-item"
          style="margin-right: 10px;float:right"
          type="primary"
          icon="el-icon-edit"
          @click="handleCreate"
        >
          添加
        </el-button>
    </div>

    <el-table
      :key="tableKey"
      :data="list"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
    <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
      <el-table-column label="活动描述" min-width="300px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.deseribe }}</span>
        </template>
      </el-table-column>
      <el-table-column :formatter='formatter' prop="startTime" label="开始时间" width="200px" align="center">
        <!-- <template slot-scope="scope">
          <span>{{ scope.row.startTime }}</span>
        </template> -->
      </el-table-column>
      <el-table-column :formatter='endFormatter' prop="endTime" label="结束时间" width="200px" align="center">
        <!-- <template slot-scope="scope">
          <span>{{ scope.row.endTime }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="活动方式" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mode==='A'?'口令码':'链接' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动状态" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status==='0'?'未开启':scope.row.status==='1'?'进行中':'已结束' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"  
        width="300px"
        class-name="small-padding fixed-width"
      > 
        <template slot-scope="{ row }">
          <el-button
            size="small"
            align="center"
            type="primary"
            @click="handleUpdate(row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            align="center"
            type="primary"
            @click="handleChange(row)"
            v-show="row.status==='0'||row.status==='1'"
          >
            {{row.status==='0'?'开启':'关闭'}}
          </el-button>
          <el-button
            size="small"
            align="center"
            type="danger"
            @click="handleDel(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      @close="loadPage"
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      append-to-body
    >
    <el-form
        ref="dataForm"
        :model="temp"
        label-position="right"
        label-width="150px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="活动描述：">
          <el-input type="textarea" v-model="temp.deseribe" />
        </el-form-item>
        <el-form-item label="开始时间：">
            <el-date-picker
                v-model="beginTime"
                value-format='yyyy-MM-dd HH:mm:ss'
                type="datetime"
                placeholder="选择开始日期时间">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间：">
            <el-date-picker
                v-model="overTime"
                value-format='yyyy-MM-dd HH:mm:ss'
                type="datetime"
                placeholder="选择结束日期时间">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="活动方式：">
          <el-select
            size="small"
            placeholder="请选择活动方式"
            clearable
            class="filter-item"
            style="width: 250px;margin-left:2%"
            v-model="temp.mode"
          >
            <el-option v-for="item in modaTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
          </el-select>
        </el-form-item>
        <el-form-item label="活动链接：">
          <el-input v-model="temp.linkAddress" />
        </el-form-item>
        <el-form-item label="活动状态：">
          <el-radio v-model="temp.status" label="0">未开始</el-radio>
          <el-radio v-model="temp.status" label="1">进行中</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createCommodity() : updateCommodity()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getWoolList,delBottom,updataForm,createForm,changeStatus } from '@/api/wool/index'// 异步请求 delLly
import { parseTime,formatDate } from '@/utils'
import Pagination from '@/components/Pagination' // 分页插件
const calendarTypeOptions = [
  { key: '0', display_name: '未开启' },
  { key: '1', display_name: '启动中' },
  { key: '2', display_name: '已结束' }
]
const modaTypeOptions = [
  { key: 'A', display_name: '口令码' },
  { key: 'B', display_name: '链接' },
]
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
const modaTypeKeyValue = modaTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  inject:["reload"],
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },
    modaFilter(type){
      return modaTypeKeyValue[type]
    }
  },
  data() {
    return {
      value1:[],
      modaTypeOptions,
      calendarTypeOptions,
      rowStatus:'',
      beginTime:'',
      overTime:'',
      tableKey: 0,
      list: null,
      total: 0,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        status:'',
        sort: '+id'
      },
      temp: {
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogPvVisible: false,
      outerVisible: false,
      pvData: [],
      downloadLoading: false,
      liaUser: null,
      rowId:"",
    }
  },
  created() {
    this.getList()
  },
  methods: {
    loadPage(){
      // setTimeout(function(){  //使用  setTimeout（）方法设定定时800毫秒
      //   window.location.reload();//页面刷新
      // },800);
      this.reload()
    },
    showBig(row){
      console.log(row)
      this.dialogible=true
      this.dialogImage=row.imageUrl
    },
    convertTime(){
      this.beginTime=parseTime(this.temp.startTime)
      console.log(this.beginTime)
      this.overTime=parseTime(this.temp.endTime)
    },
    formatter(row, column) {
      return parseTime(row.startTime);
    },
    endFormatter(row, column){
      return parseTime(row.endTime);
    },
    getList() {
      this.listLoading = true
      console.log(this.value1)
      this.listQuery.startTime=null == this.value1 ? "" : this.value1[0]
      console.log(this.listQuery.startTime)
      this.listQuery.endTime=null == this.value1 ? "" : this.value1[1]
      var params = {
        // pageConvert: true,
        pageNum: this.listQuery.pageNum-1,
        pageSize: this.listQuery.pageSize,
        status:this.listQuery.status,
        startDate: this.listQuery.startTime,
        endDate: this.listQuery.endTime
      }
      getWoolList(params).then(response => {
        this.list = response.data.content
        // console.log(this.list)
        this.total = response.data.totalElements
        // console.log(this.total)
        // Just to simulate the time of the request
      })
    },
    //删除
    handleDel(row){
        this.rowId=row.id
        this.$confirm('确定删除？ 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
            delBottom(this.rowId).then(res=>{
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.reload()
            })  
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
       
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
      }
    },
    handleCreate(){
      this.dialogStatus='create'
      this.dialogFormVisible = true
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.convertTime()
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    updateCommodity(){
      this.temp.startTime=new Date(this.beginTime).getTime()
      this.temp.endTime=new Date(this.overTime).getTime()
      updataForm(this.temp).then(res=>{
        if(res.code==='200'){
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
          this.dialogFormVisible = false
          this.getList()
        }else{
          this.$notify({
            title: '失败',
            message: '修改失败',
            type: 'danger',
            duration: 2000
          })
        }
      })
    },
    createCommodity(){
      this.temp.startTime=new Date(this.beginTime).getTime()
      this.temp.endTime=new Date(this.overTime).getTime()
      createForm(this.temp).then(res=>{
        if(res.code==='200'){
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
        this.dialogFormVisible = false
        this.getList()
        }else{
          this.$notify({
            title: '失败',
            message: '修改失败',
            type: 'danger',
            duration: 2000
          })
        }
      })
    },
    //修改状态
    handleChange(row){
      console.log(12123113)
      let rowId=row.id
      if(row.status==='0'){
        this.rowStatus='1'
      }else if(row.status==='1'){
        this.rowStatus='2'
      }
      let params={
        id:rowId,
        status:this.rowStatus
      }
      changeStatus(params).then(res=>{
        if(res.code==='200'){
            this.$notify({
              title: '成功',
              message: '修改状态成功',
              type: 'success',
              duration: 2000
            })
        this.getList()
        }else{
          this.$notify({
            title: '失败',
            message: '修改状态失败',
            type: 'danger',
            duration: 2000
          })
        }
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>